import { getAllUsersService, loginService, registerService } from '../../service/UserService';
import { routes } from '../../routes';
import Router from 'koa-router';
import Result from '../../vo/result';
import { validationMiddleware } from '../../middleware/validationMiddleware';
import { UserDto, userPageQuery } from './User.dto';
import { ResultCode } from '../../enums/resultCode';
import { connectProducer, consumer, producer } from '../../config/kafkaConfig';
import logger from '../../Logger/logger';

const router = new Router({
  prefix: '/api',
});
router.get(routes.USER_GET, async ctx => {
  const query: userPageQuery = ctx.query;
  ctx.body = await getAllUsersService(query);
});

router.post(routes.USER_LOGIN, validationMiddleware(UserDto), async ctx => {
  const body: any = ctx.request.body;
  ctx.body = await loginService(body.username);
});

router.post(routes.USER_REGISTER, validationMiddleware(UserDto), async ctx => {
  const body: any = ctx.request.body;
  ctx.body = await registerService(body.username, body.password);
});

router.get('/kafka/test', async ctx => {
  try {
    await connectProducer();
    await producer.send({
      topic: 'testTopic',
      messages: [
        { value: 'Hello Kafka' },
      ],
    });
    ctx.body = Result.success('发送成功');
  } catch (err) {
    logger.error('发送失败', err);
    ctx.body = Result.fail(ResultCode.FAIL, err);
  } finally {
    await producer.disconnect();
  }
});

router.get('/kafka/consumer', async ctx => {
  ctx.body = Result.success('消费成功');
});

export default router.routes();
